<?php

!defined('SYSTEM_INCLUDED') && exit('Access Denied');

Class IndexController extends BaseController{
	
	public function Index(){
		$this->view->display();
	}
	
	
	public function Start(){
		mt_srand((double)microtime()*1000000);
		$rand_num = mt_rand(1,200);
		Session::set('rand_num',$rand_num);
		Session::set('try_time', 0 );
		//echo $_SESSION['rand_num'];
		$this->view->assign('result','开始了！请输入。');
		$this->view->assign('try_time',0);
		$this->view->display();
	}
	
	
	
	public function Check(){
		$randNum = Session::get('rand_num');
        if(empty($randNum)){
			throw new CommonException("Session was destoryed! Please restart the game!");
		}
		$guessNum = empty($_POST['guess']) ? 0 : $_POST['guess'];
		SysBase::import('System.Validators.IntegerValidator');
		$IntegerValidator = SysBase::getInstance('IntegerValidator');
		$IntegerValidator->set('min',1);
		$IntegerValidator->set('max',200);
		$IntegerValidator->validate($guessNum);
		
		$tryTime=Session::get('try_time');
		switch ($tryTime){
			case 0:
			case 1:
			case 2:
			case 3:
			case 4:
			    if($randNum == $guessNum){
					Session::set('rand_num', null );
					$tryTime = 5;
					$this->view->assign('result',"猜中了！确实是{$randNum}恭喜恭喜！");
				}else{
				    $tryTime = $tryTime + 1;
					$this->view->assign('result','猜不中，请继续努力！');
				}
				if(5 == $tryTime && $randNum != $guessNum){
					$this->view->assign('result',"猜解机会已经用光，正确答案是{$randNum}。");
				}
				Session::set('try_time', $tryTime );
				$this->view->assign('try_time',$tryTime);
				$this->view->display('Start');
				break;
			
			case 5:
			    throw new CommonException("You have been played in one game! Please restart the game!");
			    break;
			default:
			    throw new CommonException("Unknow ERROR! Please restart the game!");
		}
	}

}